<template>
  <div class="mod-config">
    <!--路径和搜索-->
    <el-form :inline="true" >
      <el-form-item class="btn_line">
        <!-- 回退按钮-->
        <icon class="el-icon-arrow-left btn_operate" size="mini" @click="returnBtnHandle"></icon>
        <!-- 刷新按钮-->
        <icon class="el-icon-refresh btn_operate" size="mini" @click="isSearch=false,changePath(getDirByPatharr())"></icon>
      </el-form-item>
      <el-form-item label="路径：" v-if="!isSearch" >
        <el-link  @click="curpath = [],changePath('')"><strong>主目录</strong></el-link>
        <span>/</span>
        <el-link  :key="index"
                 v-for="(item,index) in curpath" @click="changePath(getFilepath(index))">
          <strong>{{ item }}</strong> <span>/</span>
        </el-link>
      </el-form-item>
      <el-form-item label="搜索结果：" v-else>
        <el-tag type="primary" closable @close="isSearch=false,changePath(getDirByPatharr())">{{searchValue}}</el-tag>
      </el-form-item>
      <!--操作-->
      <div  style="float: right;display: flex">
<!--        <uploader-btn>上传文件</uploader-btn>-->
<!--        <el-button type="success" icon="el-icon-upload2" @click="uploadFileHandle">上传文件</el-button>-->
        <div v-if = "isAuth('project:file:save')">
          <div v-for="item in this.upfileList" v-if="upfileList.length > 0">
            {{item.fileName}}: <el-progress :stroke-width="16" :percentage="item.plan"></el-progress>
          </div>
          <el-upload :action="upFileUrl"
                     :data="{'path': this.getDirByPatharr()}"
                     multiple
                     name="file"
                     ref="upload"
                     :headers="tokenHeaders"
                     :before-upload="handleBeforeUpload">
            <el-button size="small" type="success" icon="el-icon-upload2" :disabled="isSearch">上传文件</el-button>
          </el-upload>
        </div>
        <div style="margin-left: 5px" v-if = "isAuth('file:file:update')">
          <el-button type="warning" icon="el-icon-folder-add" size="small" @click="addFolderHandle" :disabled="isSearch">新建文件夹</el-button>
        </div>
        <div >
          <div style="display: flex;margin-left: 5px;">
            <el-input v-model="searchValue" size="small" clearable @keyup.enter.native="searchHandle"
                      @clear="isSearch=false,changePath(getDirByPatharr())"></el-input>
            <el-button size="small" type="primary" @click="searchHandle">搜索</el-button>
          </div>
        </div>
      </div>
    </el-form>

<!--    <el-upload :action="upFileUrl" multiple name="file" id="fileUpload"-->
<!--               :before-upload="handleBeforeUpload" :http-request="handleRequestFile" :on-change="handleChange"-->
<!--               ref="fileUpload" :headers="tokenHeaders" drag multiple :auto-upload="false" >-->
<!--&lt;!&ndash;      <i class="el-icon-upload"></i>&ndash;&gt;-->
<!--&lt;!&ndash;      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>&ndash;&gt;-->
<!--    </el-upload>-->
    <!--列表-->
    <uploader :options="options" ref="uploader" :file-status-text="statusText" class="uploader-example"
              @file-success="onFileSuccess" @file-added="onFileAdd" @file-removed="onFileRemove">
      <!--      //浏览器不支持将显示此内容-->
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <el-table :data="fileList" border :default-sort ="{prop:'fileType',order:'ascending'}" v-loading="loading" stripe :height="documentClientHeight-245">
          <template slot="empty"><span>文件夹为空</span></template>
          <el-table-column prop="fileName" header-align="center" align="left" label="文件名称" :show-overflow-tooltip="true" sortable>
            <template slot-scope="scope">
              <div class="file_item_name" @dblclick="scope.row.isFouce? '':lookoverFileHandle(scope.row)">
                <i><icon-svg :name="getFileType(scope.row)" ></icon-svg></i>
                <input v-if="scope.row.isFouce" v-model="scope.row.fileName" v-focus @blur="blurInputHandle(scope.row)"></input>
                <strong v-else>{{scope.row.fileName}}</strong>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="fileType" header-align="center" align="center" label="文件类型" sortable width="120" >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.isDir" type="primary">文件夹</el-tag>
              <el-tag v-else type="info" plain>{{scope.row.fileType.replace('.','')}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="fileSize" header-align="center" align="center" label="文件大小" sortable width="120" >
            <template slot-scope="scope">
              {{getFileSize(scope.row.fileSize)}}
            </template>
          </el-table-column>
          <el-table-column prop="filePath" header-align="center" align="center" label="文件路径" v-if="isSearch"></el-table-column>
          <el-table-column header-align="center" align="left" width="240" label="操作" >
            <template slot-scope="scope">
              <el-tooltip class="item"  :content="scope.row.isDir? '进入' : '查看'" placement="left">
                <el-button type="primary" size="mini" :icon="scope.row.isDir? 'el-icon-right' : 'el-icon-search'"
                           @click="lookoverFileHandle(scope.row)" v-if="isAuth('file:file:list')"></el-button>
              </el-tooltip>
              <el-tooltip class="item"  content="重命名" placement="left">
                <el-button type="warning" size="mini" icon="el-icon-edit-outline" @click="editFileHandle(scope.row)" v-if="isAuth('file:file:update')"></el-button>
              </el-tooltip>
              <el-tooltip class="item"  content="删除" placement="left">
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteFileHandle(scope.row)" v-if="isAuth('file:file:delete')"></el-button>
              </el-tooltip>
              <el-tooltip class="item"  content="下载" placement="left-start" v-if="!scope.row.isDir">
                <el-button type="success" size="mini" icon="el-icon-download" @click="downloadFileHandle(scope.row)"
                           v-if="isAuth('file:file:download')" :loading="scope.row.loading">
                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!--          <uploader-btn>选择文件</uploader-btn>-->
      </uploader-drop>
      <div class="popup-container">
        <div class="header">
          <div class="title_span">上传列表</div>
          <div class="title_btn" >
            <i class="el-icon-minus" @click="panelShow = false" v-if="panelShow"></i>
            <i class="el-icon-copy-document" @click="panelShow = true" v-if="!panelShow"></i>
          </div>
        </div>
        <uploader-list class="content" v-if="panelShow">
          <div class="file-panel" slot-scope="props" >
            <ul class="file-list">
              <li v-for="file in props.fileList" :key="file.id">
                <uploader-file :class="'file_' + file.id" ref="files" :file="file" :list="true"></uploader-file>
              </li>
              <div class="no-file" v-if="!props.fileList.length">
                <div style="text-align: center;color: grey">--暂无待上传文件--</div>
              </div>
            </ul>
          </div>
        </uploader-list>
      </div>
    </uploader>
  </div>
</template>

<script>
  import Vue from 'vue'
  import {getFileType} from '@/utils/others/fileutils'
  import fileWebuploader from './file-webuploader'
  import {stringIsNull} from '@/utils'

  // 注册一个全局自定义指令 `v-focus`
  Vue.directive('focus', {
    // 当被绑定的元素插入到 DOM 中时……
    inserted: function (el) {
      // 聚焦元素
      el.focus()
    }
  })
  export default {
    data () {
      return {
        id: 'dialog',
        options: {
          target: this.$http.adornUrl('/file/file/chunkUpload'),
          chunkSize: 2 * 1024 * 1024,
          testChunks: false , // 是否测试分片
          query: {
            // 传参
            token: Vue.cookie.get('token')
          }
        },
        statusText: {
          success: '成功了',
          error: '出错了',
          uploading: '上传中',
          paused: '暂停中',
          waiting: '等待中'
        },
        panelShow: false,
        timer: '',
        websock: '',
        fileData: [],  // 上传文件数据
        upfileList: [],
        fileList: [],
        curpath: [],
        searchValue: '',
        isSearch: false, // 是否为搜索
        loading: false,
        uploaderVisible: false,
        upFileUrl: window.SITE_CONFIG['baseUrl'] + '/file/file/uploadFile/',  // 文件上传地址
        tokenHeaders: { token: Vue.cookie.get('token') }  // token请求
      }
    },
    mounted () {
      this.init()
    },
    destroyed () {
      this.websock.close() // 离开路由之后断开websocket连接
      clearInterval(this.timer)
    },
    computed: {
      userId: {
        get () { return this.$store.state.user.id },
        set (val) { this.$store.commit('user/updateId', val) }
      },
      documentClientHeight: {
        get () { return this.$store.state.common.documentClientHeight }
      }
    },
    components: {
      fileWebuploader
    },
    methods: {
      init () {
        this.loading = true
        this.getFilelist('').then(filelist => {
          this.loading = false
          this.fileList = filelist
        })
        let that = this
        this.timer = setInterval(function () {
          if (that.$refs.uploader.fileList.length > 0) {
            let completed = true
            for (let fileItem of that.$refs.uploader.fileList) {
              if (!fileItem.completed) {
                completed = false
              }
            }
            console.log(completed)
            if (completed) {
              that.$refs.uploader.uploader.cancel()
            }
          }
        }, 20 * 1000)
      },
      // 上传文件
      uploadFileHandle () {
        this.uploaderVisible = true
        this.$nextTick(() => {
          this.$refs.fileWebuploader.init()
        })
      },
      getFilelist (curpath) {
        return new Promise((resolve, reject) => {
          this.$http({
            url: this.$http.adornUrl(`/file/file/list`),
            method: 'get',
            params: this.$http.adornParams({
              curpath: curpath,
              isSearch: this.isSearch,
              searchValue: this.searchValue
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              resolve(data.list)
            } else {
              this.$message.error(data.msg)
              reject(data.msg)
            }
          })
        })
      },
      // 获取文件大小
      getFileSize (size) {
        if (size > 1024 * 1024 * 1024) {
          return (size/(1024*1024* 1024)).toFixed(2) + 'GB'
        } else if (size > 1024 * 1024) {
          return (size/(1024*1024)).toFixed(2) + 'MB'
        } else if (size > 1024) {
          return (size/1024).toFixed(2) + 'KB'
        } else {
          return size + 'B'
        }
      },
      // 回退按钮
      returnBtnHandle () {
        if (this.isSearch) {
          this.isSearch = false
        } else {
          if (this.curpath.length >= 1) {
            this.curpath.pop()
          }
        }
        this.changePath(this.getDirByPatharr())
      },
      // 新建文件夹
      addFolderHandle () {
        let fileItem = {
          fileName: '',
          isDir: true,
          fileSize: 0,
          isFouce: true,
          isNew: true,
          fileType: '',
          filePath: this.getDirByPatharr()
        }
        this.fileList.splice(0,0,fileItem)
      },
      // 文本框输入失去焦点
      blurInputHandle (item) {
        if (stringIsNull(item.fileName.trim())) {
          this.fileList.shift()
        } else if (item.fileName.trim() === item.oldName) {
          this.changePath(this.getDirByPatharr())
        } else {
          this.$http({
            url: this.$http.adornUrl(`/file/file/` + (item.isNew ? 'save' : 'update')),
            method: 'post',
            data: this.$http.adornData({
              filePath: item.filePath,
              newName: item.fileName.trim(),
              oldName: item.oldName,
              isDir: item.isDir
            })
          }).then(({data}) => {
            this.changePath(this.getDirByPatharr())
            if (data && data.code === 0) {
              item.isFouce = false
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      },
      // 下载文件
      downloadFileHandle (fileItem) {
        window.location.href = window.SITE_CONFIG['downloadUrl'] + 'file/' + fileItem.filePath + '/' + fileItem.fileName
      },
      // 根据数组获取文件路径
      getDirByPatharr () {
        let cPath = ''
        this.curpath.forEach((item,index) => {
          cPath += item + '/'
        })
        return cPath
      },
      // 获取文件路径
      getFilepath (num) {
        this.curpath = this.curpath.slice(0,num + 1)
        return this.getDirByPatharr()
      },
      // 跳转路径
      changePath (path) {
        this.loading = true
        this.getFilelist(path).then(filelist => {
          this.fileList = filelist
          this.loading = false
        })
      },
      // 查看文件
      lookoverFileHandle (item) {
        this.isSearch = false
        let baseUrl = window.SITE_CONFIG['uploadUrl'] + 'file/'
        // 文件类型为 图片、pdf、word、excel、ppt、txt 可在线打开
        switch (getFileType(item)) {
          case 'FOLDER':
            let pathList = []
            for (let path of item.filePath.split('/')) {
              if (!stringIsNull(path)) pathList.push(path)
            }
            pathList.push(item.fileName)
            this.curpath = pathList
            this.changePath(this.getDirByPatharr())
            break
          case 'EXCEL':
          case 'WORD':
          case 'PPT':
            window.open('https://view.officeapps.live.com/op/view.aspx?src=' + baseUrl + item.filePath + '/' + item.fileName)
            break
          case 'TEXT':
          case 'PICTURE':
          case 'PDF':
            window.open(baseUrl + item.filePath + '/' + item.fileName)
            break
          default:
            this.$message.error('当前文件不支持在线浏览！')
            break
        }
      },
      // 编辑文件
      editFileHandle (item) {
        let fList = []
        for (let fileItem of this.fileList) {
          let newItem = {
            fileName: fileItem.fileName,
            oldName: fileItem.fileName,
            fileSize: fileItem.fileSize,
            fileType: fileItem.fileType,
            isDir: fileItem.isDir,
            isFouce: false,
            isNew: false,
            filePath: fileItem.filePath
          }
          if (item.fileName === fileItem.fileName) {
            newItem.isFouce = true
          }
          fList.push(newItem)
        }
        this.fileList = fList
      },
      // 搜索文件
      searchHandle () {
        if (stringIsNull(this.searchValue)) {
          this.$message.error('搜索关键字不能为空！')
          return
        } else {
          this.isSearch = true
          this.getFilelist('').then(list => {
            this.fileList = list
          })
        }
      },
      // 删除文件
      deleteFileHandle (item) {
        this.$confirm('是否删除文件【' + item.fileName + '】', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteFileFromApi(item)
        })
      },
      deleteFileFromApi (item) {
        this.loading = true
        this.$http({
          url: this.$http.adornUrl(`/file/file/delete`),
          method: 'post',
          data: this.$http.adornData({
            filePath: this.getDirByPatharr(),
            fileName: item.fileName,
            isDir: item.isDir
          })
        }).then(({data}) => {
          this.loading = false
          if (data && data.code === 0) {
            // this.$message({
            //   message: data.msg,
            //   type: 'success',
            //   duration: 1500
            // })
            this.changePath(this.getDirByPatharr())
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      // 上传文件成功
      onFileSuccess (rootFile, file, response, chunk) {
        this.changePath(this.getDirByPatharr())
      },
      onFileAdd (file) {
        let rPath = file.file.relativePath.substring(0,file.file.relativePath.lastIndexOf(file.file.name))
        file.relativePath = this.getDirByPatharr() + rPath
        this.panelShow = true
      },
      // 上传时移除文件
      onFileRemove (file) {
        let that = this
        // 延时两秒 删除上传未完成的 暂时文件
        if (file.completed === false) {
          setTimeout(function () {
            let confItem = {
              fileName: file.name + '.conf',
              isDir: false
            }
            that.deleteFileFromApi(confItem)
            let tempItem = {
              fileName: file.uniqueIdentifier + '_tmp',
              isDir: false
            }
            that.deleteFileFromApi(tempItem)
          },2000)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../../assets/scss/variables";
  .btn_line {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
  }
  .btn_operate:hover {
    color: $--color-primary;
    font-size: 11pt;
    font-weight: 700;
    cursor: pointer;
  }
  .file_item_name{
    background: rgba($--color-primary,0.1);
    text-align:left;
    padding: 1px;
    -moz-user-select: none;
    -webkit-user-select: none;
    -ms-user-select: none;
    -khtml-user-select: none;
    user-select: none;
    i {
      font-size: 17pt
    }
    strong {
      font-size: 11pt;
    }
  }
  .file_item_name:hover {
    color: $navbar--background-color;
    cursor: pointer;
    text-decoration: underline;
  }

  .breadcrumb-item {
    cursor: pointer;
    padding: 3px;
    strong:hover {
      color: $navbar--background-color;
      cursor: pointer;
      text-decoration: underline;
      font-weight: 700;
      font-size: 11pt;
    }
  }

  .el-container {
    position: absolute;
    height: 500px;
    width: 500px;
    border: 1px;
    top: 20%;
    left: 35%;
    border-radius: 2px;
  }

  .uploader-drop {
    position: relative;
    padding: 1px;
    overflow: hidden;
    border: 1px dashed #ccc;
    background-color: #f5f5f5;
  }

  .popup-container {
    position: fixed;
    box-shadow: -2px -4px 5px $navbar--background-color;
    border: 1px $navbar--background-color solid;
    right: 20px;
    bottom: 15px;
    z-index: 2001;
    min-width: 600px;
    -moz-user-select:none;		/* 火狐 */
    -webkit-user-select:none;	/* 谷歌 */
    -ms-user-select:none;		/* IE */
    user-select:none;
    .header {
      padding: 6px;
      background: $--color-primary;
      color: whitesmoke;
      display: flex;
      justify-content: space-between;
      width: 100%;
      .title_span {
        font-size: 15pt;
        font-weight: 700;
      }
      .title_btn{
        padding-right: 5px;
        i {
          font-size: 19pt;
          font-weight: 700;
          cursor: pointer;
        }
        i:hover{
          color: red;
        }
      }
    }
    .content {
      background: beige;
      height: 370px;
      overflow-y: auto;
    }
  }
</style>
